import { WebSocketPath } from "../../config/path";
var wsServer = `wss://${WebSocketPath}/wss`
var limitConnect = 20;//断线重连次数
var asurplusLimitConnect = limitConnect;
var timeConnect = 0;
var ws: any;

function bigScreenWebSocketInit(id: number) {
    ws = new WebSocket(wsServer)
    ws.onopen = () => {
        console.log('WebSocket connected');
        asurplusLimitConnect = limitConnect
        var message = `{"typeClass":"large_screen_datamap","type":"login","id":${id}}`;
        ws.send(message);
    };
    ws.onmessage = (message: Text) => {
        console.log('Received message:', message.data);
    };
    ws.onclose = () => {
        // 主动重连
        //判断当前登陆状态
        if (localStorage.loginToken) {
            reconnect(id)
        }
    }
    return ws;
}
// 重连
function reconnect(id: number) {
    if (asurplusLimitConnect > 0) {
        asurplusLimitConnect--;
        timeConnect++;
        console.log("第" + timeConnect + "次重连");
        setTimeout(() => {
            bigScreenWebSocketInit(id)
        }, 2000)
    }
}
function isValidJSON(text: any) {
    try {
      let result = JSON.parse(text);
      return result;
    } catch (error) {
      return false;
    }
  }

export { bigScreenWebSocketInit,isValidJSON};